package cn.amebius.simpledocker.websocket.handler;

import cn.amebius.simpledocker.config.DockerFactory;
import cn.amebius.simpledocker.entity.model.DockerClientModel;
import cn.amebius.simpledocker.exception.DockerErrorException;
import cn.amebius.simpledocker.websocket.BaseAbstractWebsocket;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.core.command.LogContainerResultCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 阿伟
 * @date 2023/8/31 20:17
 */

@Slf4j
public class ContainerLogHandler extends BaseAbstractWebsocket {

    public ContainerLogHandler(String name) {
        super(name);
    }

    // 连接建立时触发
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        initConnections(session);
        DockerClient dc = getDockerClient(session);
        String containerId = (String) session.getAttributes().get("containerId");
        try {
            dc.logContainerCmd(containerId).withStdErr(true)
                    .withStdOut(true)
                    .withFollowStream(true)
                    .withTail(100)
                    .exec(new LogContainerResultCallback() {
                              @Override
                              public void onNext(Frame item) {
                                  try {
                                      session.sendMessage(new TextMessage(item.getPayload()));
                                  } catch (IOException e) {
                                      throw new RuntimeException(e);
                                  }
                              }
                          }
                    ).awaitCompletion();
        } catch (Exception e) {
            throw new DockerErrorException("Docker异常：查看容器日志出错！");
        }
        destory(session);
    }

    // 连接关闭时触发
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status){
        destory(session);
    }




}
